<template>
  <div>
    <van-nav-bar
      title="修改手机号"
      left-text="返回"
      left-arrow
      fixed
      @click.left.native="$router.go(-1)"
    ></van-nav-bar>
    <van-cell-group class="pwd">
      <van-field
        v-model="old"
        required
        :error-message="oldState"
        label="原手机号"
        placeholder="请输入原手机号"
        size="large"
        @blur="check"
      />
      <van-field
        v-model="newphone"
        required
        :error-message="newState"
        label="新手机号"
        placeholder="请输入新手机号"
        size="large"
        @blur="checknew"
      />
    </van-cell-group>
    <van-button type="primary" @click="updatePhone" class="btn" size="large"
      >确认修改</van-button
    >
  </div>
</template>

<script>
import { mapMutations, mapState } from "vuex"
export default {
  computed: {
    ...mapState(["user"]),
  },
  data() {
    return {
      old: "",
      newphone: "",
      oldState: "",
      newState: "",
    }
  },
  methods: {
    ...mapMutations(["updateUser"]),
    check() {
      let exp = /^1[3-9]\d{9}$/
      if (exp.test(this.old)) {
        this.oldState = ""
        console.log(this.user)
        return true
      } else {
        this.oldState = "手机号格式错误"
        return false
      }
    },
    checknew() {
      let exp = /^1[3-9]\d{9}$/
      if (exp.test(this.newphone)) {
        this.newState = ""
        return true
      } else {
        this.newState = "手机号格式错误"
        return false
      }
    },
    updatePhone() {
      if (this.check() && this.checknew()) {
        console.log("验证成功,开始修改手机号")
        const url = "user/phone"
        const params = `unames=${this.user.data.unames}&oldphone=${this.old}&newphone=${this.newphone}`
        this.axios.post(url, params).then(res => {
          console.log(res)
          if (res.data.code) {
            this.$dialog
              .alert({
                message: "修改手机号成功",
              })
              .then(() => {
                this.$store.commit("updateUphone", res.data.data)
                this.$router.push("/home/personal")
              })
          } else {
            this.$dialog.alert({
              message: "修改手机号失败,请重试",
            })
          }
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.pwd {
  margin-top: 14vw;
}
.btn {
  display: block;
  margin: 5vw 0;
}
</style>
